# -*- coding: utf-8 -*-
import sys
import os
import requests
import json

reload(sys)
sys.setdefaultencoding('utf-8')


def send_post(url, payload):
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'locahost/genghz',
    }

    res = requests.post(url,
                        headers=headers,
                        data=json.dumps(payload))

    return res.content


def download(url, path, name):
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'locahost/genghz',
    }
    r = requests.get(url,
                     headers=headers,
                     stream=True)

    if r.status_code == 200:
        with open(path + '/' + name, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)
                    f.flush()
            f.close()


if __name__ == "__main__":
    # 读文件
    path = '/Users/ghz/Desktop/python/qr_url.txt'
    f = open(path)
    content = f.readlines()
    f.close()

    qr_url_map = {}
    for qr_url in content:
        url = qr_url.strip('\n')
        qr = url.split('/to/')[1]
        qr_url_map[qr] = url

    for qr in qr_url_map:
        download_url = send_post(
            'http://genqr.kuaihaowei.net/qr/common', {'name': 'ali2-' + qr, 'url': qr_url_map[qr]})

        print qr, qr_url_map[qr], download_url
        download(download_url, '/Users/ghz/Desktop/python/qr', qr + '.png')
